<?php
/**
 * ws 优化 基础类库
 * Created by PhpStorm.
 * User: 庆金
 * Date: 2019-12-13
 * Time: 21:00
 */
use Swoole\Coroutine\System;

class Ws{
    CONST HOST = '0.0.0.0';
    CONST PORT = 8812;
    public $ws = null;
    public function __construct(){
        $this->ws = new swoole_websocket_server(Ws::HOST,Ws::PORT);
        $this->ws->set([
           'worker_num' =>  2,
            'task_worker_num'   =>  2,
        ]);
        $this->ws->on("open",[$this,'onOpen']);
        $this->ws->on('message',[$this,'onMessage']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('close',[$this,'onClose']);
        $this->ws->start();
    }

    /**
     * 监听ws链接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws,$request){
        var_dump($request->fd);
        if ($request->fd == 1){
            // 每2秒执行一次
            swoole_timer_tick(2000,function ($timer_id){
               echo "2s: timerId:{$timer_id}";
            });
        }
    }

    /**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws,$frame){
        echo "ser-push-message:{$frame->data}\n";
        // 需要 10 s 执行
        $data = [
            'task'  => 1,
            'fd'    => $frame->fd
        ];
        $filename = __DIR__."/access.log";
        $content = [
            'date:' =>  date("Y-m-d H:i:s"),
            'data:'  =>  $frame
        ];
        $content = json_encode($content);
        $this->addLog($filename,$content);
        // 异步任务
//        $ws->task($data);

        swoole_timer_after(5000,function () use($ws, $frame){
            echo '5s-after\n';
            $ws->push($frame->fd,'server-timer-after');
        });
        $ws->push($frame->fd,"server-push:".date("Y-m-d H:i:s"));
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $workId
     * @param $data
     */
    public function onTask($serv,$taskId,$workId,$data){
        print_r($data);
        //耗时场景
        sleep(10);
        // 返回内容告诉work进程
        return "on task finish";
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $data onTask return的内容
     */
    public function onFinish($serv,$taskId,$data){
        echo "taskId:{$taskId}\n";
        echo "finish-data-success:{$data}\n";
    }

    public function onClose($ws,$fd){
        echo "clientid:{$fd}\n";
    }

    private function addLog($filename,$content){

//        $filename = __DIR__ . "/1.log";
        go(function () use ($filename,$content)
        {
            // FILE_APPEND 追加，如果不填写则为替换
            $r =  System::writeFile($filename, $content.PHP_EOL,FILE_APPEND);
            echo "success".PHP_EOL;
//    var_dump($r);
        });
    }


}

$obj = new Ws();